package net.lesscoding.protocol;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.lesscoding.rpc.codec.ClassCodec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author eleven
 * @date 2024/12/2 17:27
 * @apiNote 扩展序列化反序列化
 */
public interface Serializer {

    <T> T deserialize(Class<T> clazz, byte[] bytes);

    <T> byte[] serialize(T object);

    enum Algorithm implements Serializer {
        JAVA{
            @Override
            public <T> T deserialize(Class<T> clazz, byte[] bytes) {
                try {
                    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
                    return  (T) ois.readObject();
                } catch (Exception e) {
                    throw  new RuntimeException("反序列化失败", e);
                }

            }

            @Override
            public <T> byte[] serialize(T object) {
                try {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(baos);
                    oos.writeObject(object);
                    return baos.toByteArray();
                } catch (Exception e) {
                    throw new RuntimeException("序列化失败", e);
                }
            }
        },
        JSON{
            private Gson gson = new GsonBuilder()
                    .registerTypeAdapter(Class.class, new ClassCodec())
                    .create();;
            @Override
            public <T> T deserialize(Class<T> clazz, byte[] bytes) {
                return gson.fromJson(new String(bytes, StandardCharsets.UTF_8), clazz);
            }

            @Override
            public <T> byte[] serialize(T object) {
                return gson.toJson(object).getBytes(StandardCharsets.UTF_8);
            }
        }
        ;
    }
}
